package net.sk.cam;

import java.net.InetSocketAddress;

import net.bat.db.BaseDAOImpl;
import net.bat.util.Cfg;
import net.sk.mina.imagine.FrameHeader;
import net.sk.mina.imagine.ImageRequest;
import net.sk.mina.imagine.ImageResponse;
import net.sk.mina.imagine.client.ImageListener;

import org.apache.mina.core.RuntimeIoException;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.SocketConnector;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import dao.hb.ODevice;
import dao.hb.UUser;


public class CtrlClient extends IoHandlerAdapter {
	
    private String host;
    private int port;
    private SocketConnector connector;
    private IoSession session;
    private ODevice od=null;
	//心跳帧回送
	static public final int ack= 0x55AA55AA;
    public static final int CONNECT_TIMEOUT = 3000;
    public static final int CONNECT_SPAN = 10000;
    public static final int PORT_CTRL = 8886;
	
    public CtrlClient(ODevice od, int port) {
    	this(od.getIpAddr(),port);
    	this.od = od;
    }
    public CtrlClient(String host, int port) {
        this.host = host;
        this.port = port;
        connector = new NioSocketConnector();
        connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new CamCtrlFactory()));
        connector.setHandler(this);
    }

    public boolean isConnected() {
        return (session != null && session.isConnected());
    }

    public void connect() {
        ConnectFuture connectFuture = connector.connect(new InetSocketAddress(host, port));
        connectFuture.awaitUninterruptibly(CONNECT_TIMEOUT);
        try {
            session = connectFuture.getSession();
        }
        catch (RuntimeIoException e) {
            //reconnect();
        }
    }

    public void reconnect(){
        try {
			Thread.sleep(CONNECT_SPAN);
			connect();
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}    	
    }
    public void disconnect() {
        if (session != null) {
            session.close(true).awaitUninterruptibly(CONNECT_TIMEOUT);
            session = null;
        }
    }

    public void sessionOpened(IoSession session) throws Exception {
    	//发送参数读取命令
    	CtrlReq req = new CtrlReq(0xFF,0x00,0x03);
    	sendRequest(req);
    }

    public void sessionClosed(IoSession session) throws Exception {
    }

    public void sendRequest(CtrlReq req) {
        if (session == null) {
            //noinspection ThrowableInstanceNeverThrown
        } else {
            session.write(req);
        }
    }

    public void messageReceived(IoSession session, Object message) throws Exception {
        String rstr = (String) message;
        //TODO set device info.
        od.setRemark(rstr);
		BaseDAOImpl bdi = (BaseDAOImpl) Cfg.getBean("BaseDAOImpl");
		bdi.update(od);
    }
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        disconnect();
        reconnect();
    }
    
}
